//
//  JointUtils.swift
//  SmartCheckIn
//
//  Created by CidyChou on 2017/8/17.
//  Copyright © 2017年 CidyChou. All rights reserved.
//

import Foundation

class CabineUtils {
    
    //let bluetoothName = "#0004ed5003dbca44c"
    var phone:String
    var array = [UInt8]()
    var bluetoothArray = [String]()
    
    
    var WgpCount:Int
    var sum = 0x00
    
    init(phone p : String,dicBluetooth dic : Dictionary<String, Int>) {
        self.phone = p
        
        var array = [String]()
        
        
        let sortedDicKey = dic.sorted{ (k1, k2) ->Bool in
            
            return k1.value > k2.value
            
        }
        print("排序后的字典:  -- > \(sortedDicKey)")
        let keys = sortedDicKey
        for key in keys{
            print(key.key)
            array.append(key.key)
        }
        
        self.bluetoothArray = array
        self.WgpCount = array.count
    }
    
    
    func getBluetoothArray() -> [String] {
        return bluetoothArray
    }
    
    
    func getFrame(ord : Int) -> [UInt8] {
        
        array.append(0xFA)
        array.append(0xFB)
//        array.append(0x0A+(UInt8(WgpCount*9)))//LEN
        array.append(0x0D+(UInt8(WgpCount*9)))//LEN
//        sum += (0x0A+(WgpCount*9))
        sum += (0x0D+(WgpCount*9))
        array.append(0x49) //Ord
        sum += 0x49
        array.append(UInt8(ord)) //SegOrd
        sum += ord
       // array.append(0x07) //SegOrd
       //sum += 0x07
        
        //phone2UInt8(phone: phone)//拼接手机
        let phoneHex = String(Int(phone)!,radix:16)
        stringToByte(HexString: phoneHex, byteCount: 8)
        //print(bluetoothArray)
        
        //添加判空！！！！！
        array.append(UInt8(bluetoothArray.count)) // 终端数
        sum += bluetoothArray.count
        
        for var i in 0 ..< bluetoothArray.count{
            
            //btName2UInt8(bluetoothName: bluetoothArray[i])
            stringToByte(HexString:  bluetoothArray[i][1..<18], byteCount: 9)
        }
        
        
        let u = UInt8(sum & 0x7f)
        array.append(u)//sum
        
        return array
    }
    
    func phone2UInt8(phone p:String){
        let myint = Int(phone)
        let str2 = "0"
        
        var str =  str2.appending(String(myint!,radix:16))
        
        while str.count < 10 {
            str = str2.appending(str)
        }
        var end = 0
        //str.characters.count/2
        for var i in 0..<5{
            end += 2
            i *= 2
            
            let phoneByte = str[i..<end]
            let value = hexStringToInt(from: phoneByte)
            
            array.append(UInt8(value))
            sum += value
        }
    }
    
    
    func stringToByte(HexString str:String,byteCount count:Int){
        var newString  = str
        while newString.count < count*2 {
            newString = "0".appending(newString)
        }
       // print("newString",newString)
        
        var end = 0
        for var i in 0..<count{
            end += 2
            i *= 2
            
            let oneByteString = newString[i..<end]
            let mByte = hexStringToInt(from: oneByteString)
            if mByte == 252{
                let newHexInt = (mByte+0x80)&0xff
                array.append(UInt8(newHexInt))
                sum += newHexInt
                array.append(UInt8(0xfc))
                continue
            }
            array.append(UInt8(mByte))
            sum += mByte
        }
        
    }
    
    
    func btName2UInt8(bluetoothName btn:String){
        
        let strr = "0\(btn[1..<18])"
        
//        strr[0..<2])
//        print(array)
        var end = 0
        for var i in 0..<9{
            end += 2
            i *= 2
            
            let btn = strr[i..<end]
            //print(bt)
            let bt = hexStringToInt(from: btn)
            array.append(UInt8(bt))
            sum += bt
        }
    }
    
    
    func hexStringToInt(from:String) -> Int {
        let str = from.uppercased()
        var sum = 0
        for i in str.utf8 {
            sum = sum * 16 + Int(i) - 48 // 0-9 从48开始
            if i >= 65 {                 // A-Z 从65开始，但有初始值10，所以应该是减去55
                sum -= 7
            }
        }
        return sum
    }
}

// 截取string
extension String {
    subscript(r: Range<Int>) -> String {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound);
            let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
            return self.substring(with: Range(startIndex..<endIndex))
        }
        set {
            let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound);
            let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
            self.replaceSubrange(Range(startIndex..<endIndex), with: newValue)
        }
    }
}
